<template>
	<view>
		<view style="margin: 20rpx 20rpx 0rpx 20rpx;" v-if="btnShow">
			<u-button text="新增" type="primary" @click="onAdd"></u-button>
		</view>
		<template v-if="dataList && dataList.length">
			<view class="inforamtion" style="display: flex;" v-for="(item, index) in dataList" :key="index">
				<view >
					<view class="option" style="width: 520rpx;">
						<view class="lf">业务编码</view>
						<view class="rl">{{ item.categoryCode }}</view>
					</view>
					<view class="option" style="width: 520rpx;">
						<view class="lf">业务名称</view>
						<view class="rl">{{ item.categoryName }}</view>
					</view>
					<view class="option" style="width: 520rpx;">
						<view class="lf">合同占比（%）</view>
						<view class="rl">{{ item.contractRate }}</view>
					</view>
					<view class="option" style="width: 520rpx;">
						<view class="lf">分配合同额（元）</view>
						<view class="rl">{{ item.contractAmount }}</view>
					</view>
					<view class="option" style="width: 520rpx;">
						<view class="lf">切割合同额（元）</view>
						<view class="rl">{{ item.cutContractAmount }}</view>
					</view>
					<view class="option" style="width: 520rpx;">
						<view class="lf">生产团队</view>
						<view class="rl">{{ item.productTeam ? filterMultiDictText(dictOptions['productTeam'], item.productTeam + '') : '' }}</view>
					</view>
					<!-- <view class="option" style="width: 520rpx;">
						<view class="lf">生产公司</view>
						<view class="rl">{{ item.productCompanyId ? filterMultiDictText(dictOptions['gsda'], item.productCompanyId + '') : '' }}</view>
					</view> -->
					<view class="option" style="width: 520rpx;">
						<view class="lf">团队负责人</view>
						<view class="rl"> {{ item.teamLeader ? filterMultiDictText(dictOptions['teamLeader'], item.teamLeader + ''): ''}}</view>
					</view>
					<view class="option" style="width: 520rpx;">
						<view class="lf">任务说明</view>
						<view class="rl">{{ item.taskDescription }}</view>
					</view>
					
				</view>
				<view  style="flex: 1; display: flex; align-items: center; justify-content: flex-end;" v-if="chiefEngineerOffice">
					<u-icon name="edit-pen-fill" color="#2979ff" size="20" @click="onEdit(item, index)"></u-icon>
					<u-line  direction="col" length="20" margin="0 10rpx" v-if="item.version === null || item.version === undefined || item.version === 0"></u-line>
					<u-icon v-if="item.version === null || item.version === undefined || item.version === 0" name="trash-fill" color="#2979ff" size="20"  @click="onDelete(item, index)"></u-icon>
				</view>
			</view>
		</template>
		<view v-else>
			<u-empty
				mode="data"
				text="暂无数据"
				icon="/static/empty/data.png"
			></u-empty>
		</view>
		
		<!-- 弹窗表单 -->
		<u-popup :show="showPopupInput" @close="closePopupInput" :round="10">
			<h3 class="title">
				分配项信息
			</h3>
			<view style="max-height: 80vh; background-color: #ffffff; border-radius: 10px; overflow-y: auto;">
				<view style="background-color: #ffffff; border-radius: 10px; padding: 30rpx;">
					<u--form
						:rules="rules"
						labelPosition="top"
						:model="model"
						ref="form"
						labelWidth="auto"
						:labelStyle="{
							fontSize: '14px',
							color: '#B2B2B2',
							lineHight: '20px'
						}"
					>
						<u-form-item
							label="业务分类编码"
							prop="categoryCode"
							:borderBottom="false"
							ref="item1"
							required
							@click="onChoice"
						>
							<u--input
								disabled
								v-model="model.categoryCode"
								placeholder="请选择业务分类"
								border="surround"
								suffixIcon="arrow-down-fill"
								:suffixIconStyle="{color: '#B2B2B2'}"
								:disabledColor="disabled? '#f5f7fa' : '#ffffff'"
							></u--input>
						</u-form-item>
						<u-form-item
							label="业务分类名称"
							prop="categoryName"
							:borderBottom="false"
							ref="item1"
							required
						>
							<u--input
								disabled
								v-model="model.categoryName"
								placeholder="请输入业务分类名称"
								border="surround"
								:suffixIconStyle="{color: '#B2B2B2'}"
							></u--input>
						</u-form-item>
						
						<u-form-item
							label="合同占比(%)"
							prop="contractRate"
							:borderBottom="false"
							ref="item1"
							required
						>
							<u--input
								:disabled='distributionMethod=="2" || hasReceiptContract'
								type="number"
								v-model="model.contractRate"
								placeholder="请输入合同占比"
								border="surround"
								:suffixIconStyle="{color: '#B2B2B2'}"
								@change="handleRateChange"
								@focus="handleRateFocus"
							></u--input>
						</u-form-item>
						<u-form-item
							label="分配合同额(元)"
							prop="contractAmount"
							:borderBottom="false"
							ref="item1"
							required
						>
							<u--input
								:disabled='distributionMethod=="1" || hasReceiptContract'
								type="number"
								v-model="model.contractAmount"
								@change="handleAmountChange"
								@focus="handleAmountFocus"
								placeholder="请输入分配合同额"
								border="surround"
								:suffixIconStyle="{color: '#B2B2B2'}"
							></u--input>
						</u-form-item>
						<u-form-item
							label="切割合同额(元)"
							prop="cutContractAmount"
							:borderBottom="false"
							required
						>
							<u--input
							  :disabled='hasReceiptContract'
								type="number"
								v-model="model.cutContractAmount"
								placeholder="请输入切割合同额"
								border="surround"
								@blur="handleCutAmountFocus"
								:suffixIconStyle="{color: '#B2B2B2'}"
							></u--input>
						</u-form-item>
						<u-form-item
							label="生产团队"
							prop="productTeam"
							:borderBottom="false"
							ref="item1"
							required
						>
							<h-select-team-input-popup
								:disabled="disabled"
							  style="width: 100%"
							  v-model="model.productTeam"
							  objectField="model.productTeam"
							  placeholder="请选择生产团队"
							  border="surround"
							  suffixIcon="arrow-down-fill"
							  :suffixIconStyle="{color: '#B2B2B2'}"
							  :tdlx="2"
							  @select="productTeamChange"/>
							
						</u-form-item>
						<!-- <u-form-item
								label="生产公司"
								prop="productCompanyId"
								:borderBottom="false"
								required>
								<h-select-company-input
									disabled
									style="width: 100%"
									v-model="model.productCompanyId"
									border="surround"
									placeholder="请选择生产公司"
									suffixIcon="arrow-down-fill"
									:suffixIconStyle="{color: '#B2B2B2'}"
									objectField = 'managerTrusteeForm.gsdaId'
								></h-select-company-input>
              </u-form-item> -->
						<u-form-item
							label="团队负责人"
							prop="teamLeader"
							:borderBottom="false"
							ref="item1"
							required
						>
							<h-select-person-input-popup
							  v-model="model.teamLeader"
								:disabled="disabled"
							  style="width: 100%"
							  placeholder="请选择团队负责人"
							  border="surround"
							  suffixIcon="arrow-down-fill"
							  :suffixIconStyle="{color: '#B2B2B2'}"
							  @select="teamLeaderChange"/>
						</u-form-item>
						<u-form-item
							label="任务说明"
							prop="taskDescription"
							:borderBottom="false"
							ref="item1"
						>
							<u--textarea
								
								v-model="model.taskDescription"
								confirmType="done"
								placeholder="请输入任务说明"
								:maxlength="500"
							></u--textarea>
						</u-form-item>
						
					</u--form>
					<view style="padding:20rpx 0;">
						<u-button text="确定" type="primary" @click="onConfirmPopupInput"></u-button>
					</view>
				</view>
			</view>
		</u-popup>
		<qian-tree
			ref="qiantree" 
			lazy
			:multiple="false" 
			:range="getFilesBusinessCategoryList" 
			:foldAll="true"
			selectParent
			idKey="categoryCode"
			rangeKey="categoryName"
			@confirm="treeConfirm"
			@cancel="treeCancel"
		></qian-tree>
	</view>
</template>

<script>
import http from '@/utils/request/index'
import qianTree from '@/components/qian-tree/qian-tree.vue';
import { filterMultiDictText, initDictOptions } from '@/utils/JDictSelectUtil.js'
import {
	filesBusinessCategoryList, // 业务分类列表
	
} from '@/api/index.js'
export default {
	props: {
		dataList: {
			type: [Array],
			default: () => [],
		},
		assignedAmount: {
			type: [Number, String],
			default: '',
		},
		 // 1:按比例，2：按金额
		distributionMethod: {
		  type: [Number, String],
		  default: ''
		},
		// 当有收款合同档案则不显示新增和编辑按钮
		btnShow: {
		  type: Boolean,
		  default: false
		},
		hasReceiptContract: {
		  type: Boolean,
		  default: false
		},
		chiefEngineerOffice: {
		  type: Boolean,
		  default: true
		},
	},
	data() {
		return {
			showPopupInput: false, // 表单弹窗
			getFilesBusinessCategoryList: [], // 业务分类列表
			model: {
				categoryCode: '',
				categoryName: '',
				contractRate: '',
				contractAmount: '',
				cutContractAmount:'',
				productTeam: '',
				teamLeader: '',
				taskDescription:''
			},
			disabled: false, // 是否禁用
			
			dictOptions: {},
			filterMultiDictText,
			
			rules: {
				categoryCode: [
					{ required: true, message: '请选择业务分类!', trigger: ['change','blur'], },
				],
				categoryName: [
					{ required: true, message: '请输入业务分类名称!', trigger: ['change','blur'], },
				],
				contractRate: [
					{ type: 'number', required: true, message: '请输入合同占比!', trigger: ['blur', 'change'] },
					{ pattern: /^-?(([0-9]*(\.[0-9]{1,3})$)|([0-9]+$))/, message: '请输入正确的合同占比!', trigger: ['blur'], }
				],
				contractAmount: [
					{ type: 'number', required: true, message: '请输入分配合同额!', trigger: ['blur', 'change'] },
					{ pattern: /^-?(([0-9]*(\.[0-9]{1,3})$)|([0-9]+$))/, message: '请输入正确的金额!', trigger: ['blur'], }
				],
				cutContractAmount: [
					{ type: 'number', required: true, message: '请输入切割合同额!', trigger: ['blur', 'change'] },
					{ pattern: /^-?(([0-9]*(\.[0-9]{1,3})$)|([0-9]+$))/, message: '请输入正确的金额!', trigger: ['blur'], }
				],
				productTeam: [
					{ required: true, message: '请输入生产团队!', trigger: ['change','blur'], }
				],
				teamLeader: [
					{ required: true, message: '请输入团队负责人!', trigger: ['change','blur'], }
				]
			},
			addOrEdit: 'add', // 编辑or添加
			isHandleRateChange: false, // 合同占比是否在变化
			isHandleAmountChange: false, // 合同分配額是否在变化
		};
	},
	components: {
		qianTree
	},
	onLoad(options) {
		this.getList()
		this.initDictConfig()
	},
	watch: {
		dataList: {
			handler (val) {
				this.initDictConfig()
			},
			deep: true,
			immediate: true
		}
	},
	methods: {

     
		handleCutAmountFocus(){
			if (this.model.cutContractAmount) {
        // 将输入值转换为数字，保留两位小数
        let num = Number(this.model.cutContractAmount);
        if (!isNaN(num)) {
          this.model.cutContractAmount = num.toFixed(2);
        }
      }
			// this.$set(this.model, 'cutContractAmount', Number(this.model.cutContractAmount.toFixed(2)))
		},

		// 获取业务分类列表
		getList() {
			filesBusinessCategoryList().then(res => {
				if (res.success) {
					this.getFilesBusinessCategoryList = res.result
				}
			})
		},
		
		initDictConfig() {
       
			initDictOptions('erp_company_files,file_name,id').then((res) => {
        if (res.success) {
          this.$set(this.dictOptions, 'gsda', res.result)
        }
      })

		  initDictOptions('erp_omc_team_manager,alias_name,id').then((res) => {
		    if (res.success) {
		      this.$set(this.dictOptions, 'productTeam', res.result)
		    }
		  })
		  initDictOptions('erp_employee_file,name,id').then((res) => {
		    if (res.success) {
		      this.$set(this.dictOptions, 'teamLeader', res.result)
		    }
		  })
		},
		
		// 新增
		onAdd () {
			
			if(!this.distributionMethod){
				return this.$u.toast('请选择分配方式！')
			}
			if (parseInt(this.assignedAmount) !== 0) {
				if (!this.assignedAmount) {
					return this.$u.toast('请输入预计合同额！')
				}
			}
			this.addOrEdit = 'add'
			this.model = {
				categoryCode: '',
				categoryName: '',
				contractRate: '',
				contractAmount: '',
				cutContractAmount: '',
				productTeam: '',
				teamLeader: '',
				taskDescription:''
			}
			this.getList()
			this.showPopupInput = true
			this.disabled = false // 解除禁用
		},
		// 编辑
		onEdit (item, index) {
			this.addOrEdit = 'edit'
			this.model = {...item}
			if (item.version === null || item.version === undefined || item.version === 0) {
				this.disabled = false
			} else {
				this.disabled = true
			}
			this.getList()
			this.showPopupInput = true
		},
		// 删除
		onDelete (item, index) {
			var _this = this
			uni.showModal({
				content: '确定删除吗？',
				success (res) {
						if (res.confirm) {
							// _this.dataSource.splice(index, 1);
							_this.$emit('ok', index,'delete')
							
						} else if (res.cancel) {
							// 用户点击取消
						}
					}
			})
			
		},
		closePopupInput () {
			this.showPopupInput = false
		},
		
		// 根据合同占比获取分配合同额
		handleRateChange(e){
			if (this.isHandleRateChange !== null || this.isHandleRateChange !== ''){
				if(this.assignedAmount !== 0){
					let amount = this.assignedAmount * e / 100
					this.model.contractAmount = Math.round((amount + Number.EPSILON) * 100) / 100;
					// if (!this.model.contractAmount) {
					// 	this.model.contractAmount = null
					// }
				} else {
					this.model.contractAmount = 0
				}
			}
		},
		handleRateFocus () {
			this.isHandleRateChange = true
			this.isHandleAmountChange = false
		},
		
		// 根据分配合同额获取合同占比
		handleAmountChange (e) {
			if (this.isHandleAmountChange !== null || this.isHandleAmountChange !== '') {
				if(this.assignedAmount !== 0){
					let rate = e / this.assignedAmount * 100
					this.model.contractRate = Math.round((rate + Number.EPSILON) * 100) / 100;
					// if (!this.model.contractRate) {
					// 	this.model.contractRate = null
					// }
				} else {
					this.model.contractRate = 0
				}
			}
		},
		handleAmountFocus () {
			this.isHandleAmountChange = true
			this.isHandleRateChange = false
		},
		
		productTeamChange (val) {
			this.$set(this.model, 'productTeam_dictText', val.data.aliasName)
			this.$set(this.model, 'productTeam', val.id)
			this.$set(this.model, 'teamLeader', val.data.tdfzr)
			this.$set(this.model, 'teamLeader_dictText', val.data.tdfzr_dictText)
			this.$set(this.model, 'productCompanyId', val.data.belongCompanyId)
		},
		teamLeaderChange(val){
			this.$set(this.model, 'teamLeader', val.id)
			this.$set(this.model, 'teamLeader_dictText', val.data[0].realname)
		},
		onConfirmPopupInput () {
			this.$refs.form.validate().then(res => {
				if(res){
					http.get('/api/erp/omc/project/erpOmcProjectApply/valdateProductTeamLeader', { teamId: this.model.productTeam }).then((resp) => {
						if (resp.success) {
							if (!this.model.id) {
								this.model.id = parseInt(Math.random() * 1000000000000);
							}
							this.showPopupInput = false
							this.$emit('ok', this.model,this.addOrEdit)
						} else {
							uni.showToast({
								title: resp.message,
								icon: 'none'
							})
						}
					})
				}
			})
		},
		
		// 点击选择
		onChoice () {
			if (this.disabled) {
				return false
			}
			this.showPopupInput = false
			this.$refs.qiantree._show();
		},
		
		treeConfirm (item, index) {
			this.$set(this.model, 'categoryCode', item[0].id)
			var serviceName = ''
			if (item[0] && item[0].parents && item[0].parents.length) {
				serviceName = item[0].parents[0].name + '/' + item[0].name
			} else {
				serviceName = item[0].name
			}
			
			this.$set(this.model, 'categoryName', serviceName)
			this.showPopupInput = true
		},
		treeCancel () {
			this.showPopupInput = true
		}
	}
};
</script>

<style lang="scss" scoped>
	.inforamtion{
		margin-top: 10rpx;
		padding: 10rpx;
		border-radius: 15rpx;
		box-shadow: 0px 4px 20px 0px rgba(0,0,0,0.1);
	}
	.title{
		display: flex;
		align-items: center;
		justify-content: center;
		padding: 20rpx;
	}
</style>